package com.example.logTracer.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;

import java.io.IOException;
import java.util.Map;

/**
 * @Describe : 处理链路出流HTTP请求头
 * @Author : zyx
 * @Date : 2023/10/8 17:13
 * @Version : 1.0
 **/
@Slf4j
public class HeadClientHttpRequestInterceptor implements ClientHttpRequestInterceptor {

    private static final String TRACE_ID = "traceId";
    private static final String SPAN_ID = "spanId";

    @Override
    public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] bytes, ClientHttpRequestExecution clientHttpRequestExecution) throws IOException {
        HttpHeaders headers = httpRequest.getHeaders();
        Map<String, String> contextMap = MDC.getCopyOfContextMap();

        headers.set(TRACE_ID,contextMap.get(TRACE_ID));
        headers.set(SPAN_ID,contextMap.get(SPAN_ID));
        ClientHttpResponse response = clientHttpRequestExecution.execute(httpRequest, bytes);
        return response;
    }
}
